#include "bs_video_saver.h"
#include "video_generater.h"

#include <yaml-cpp/yaml.h>

/*
    使用bs_video_saver进行保存视频的例子
*/

int main(int argc, char **argv)
{
    // 读取yaml配置文件
    /* -----------------------------------------------------*/
    if (argc < 2)
    {
        fmt::print("usage: rtsp_pusher_demo [config]\n");
        return -1;
    }

    std::string config_path = argv[1];

    YAML::Node yaml_cfg;
    try
    {
        yaml_cfg = YAML::LoadFile(config_path);
    }
    catch (YAML::BadFile &e)
    {
        fmt::print("read yaml error!\n");
        return -1;
    }

    std::string name = yaml_cfg["name"].as<std::string>();
    int width = yaml_cfg["width"].as<int>();
    int height = yaml_cfg["height"].as<int>();
    int fps = yaml_cfg["fps"].as<int>();
    int bitrate = yaml_cfg["bitrate"].as<int>();
    std::string encoder = yaml_cfg["encoder"].as<std::string>();

    fmt::print("read yaml OK!\n");
    /* -----------------------------------------------------*/



    // 调用setup进行初始化并使用write保存图像
    /* -----------------------------------------------------*/
    cv::Mat image(height, width, CV_8UC3);
    VideoGenerater mVideoGenerater(width, height);
    BsVideoSaver mBsVideoSaver;

    if (!mBsVideoSaver.setup(name, width, height, fps, encoder, bitrate))
    {
        std::cout << "mBsVideoSaver.start fail!\n";
        return -1;
    }
    std::cout << "mBsVideoSaver.start success!\n";

    auto start_time = std::chrono::steady_clock::now();
    auto cnt_time = std::chrono::steady_clock::now();

    // 推流100s
    while (std::chrono::duration_cast<std::chrono::seconds>(cnt_time - start_time).count() < 10)
    {
        // 生成图像
        mVideoGenerater.genRGBFrame(image);
        mBsVideoSaver.write(image);
        std::this_thread::sleep_for(std::chrono::milliseconds(1000 / fps));
        cnt_time = std::chrono::steady_clock::now();
    }

    mBsVideoSaver.stop();
    std::cout << "mBsVideoSaver.stop success!\n";
    /* -----------------------------------------------------*/




    return 0;
}
